
<?php
require_once ('BasicController.php');

class AdminController extends BasicController
{
	public function init ()
	{
		$this->_helper->layout->setLayout('admin-layout');
		if(!Zend_Auth::getInstance()->getStorage()->read()) {
			$this->_redirect('../error?error=404');
		} else {
			$user = Zend_Auth::getInstance()->getStorage()->read();
			$this->view->user = $user;

			if($user['user_type'] == 2){
				$this->_redirect('../error?error=404');
			}
		}
	}

	public function indexAction ()
	{
		$this->_redirect('/admin/list-products');
	}

	//LISTA OS PRODUTOS NO PAINEL DE ADMIN
	public function listProductsAction(){
		$user = Zend_Auth::getInstance()->getStorage()->read();
		$adminBusiness = new AdminBusiness();
		Zend_Registry::get('adminLog')->info($user['name'].' Iniciou tela administrativa: ');

		$listaAll = $adminBusiness->getProducts(null);
		$this->view->listAll = $this->generatePaginate ( $listaAll );
		$this->view->listEnterprises = $adminBusiness->getAllEnterprises();
		$this->view->listCategories = $adminBusiness->getAllCategories();
	}

	//LISTA OS CLIENTES NO PAINEL DE ADMIN
	public function listClientsAction(){
		$user = Zend_Auth::getInstance()->getStorage()->read();
		Zend_Registry::get('adminLog')->info($user['name'].' Iniciou tela administrativa / listagem de clientes: ');
		$adminBusiness = new AdminBusiness();

		$this->view->listClients = $this->generatePaginate ( $adminBusiness->getAllClients() );
	}

	//LISTA AS TRANSAÇÕES NO PAINEL DE ADMIN
	public function listTransactionsAction(){
		
		$this->view->city = $this->getRequest()->getParam('city');
		
		$user = Zend_Auth::getInstance()->getStorage()->read();
		Zend_Registry::get('adminLog')->info($user['name'].' Iniciou tela administrativa / listagem de transações: ');
		$adminBusiness = new AdminBusiness();

		$this->view->listStatus = $adminBusiness->getStatus();

		$this->view->listTransactions = $this->generatePaginate ( $adminBusiness->getAllTransactions($this->view->city) );

	}

	//ACTION PARA PESQUISA DE PRODUTOS
	public function searchProductAction ()
	{
		$adminBusiness = new AdminBusiness();

		$search = $this->getRequest()->getParam ("search");

		$listaAll = $adminBusiness->getProducts($search);

		$this->view->listAll = $this->generatePaginate ( $listaAll );
		$this->view->listEnterprises = $adminBusiness->getAllEnterprises();
		$this->view->listCategories = $adminBusiness->getAllCategories();
	}
	
	//ACTION PARA PESQUISA DE CLIENTES
	public function searchClientAction ()
	{

		$adminBusiness = new AdminBusiness();

		$search = $this->getRequest()->getParam ("searchCli");

		$listaAll = $adminBusiness->getClients($search);

		$this->view->listClients = $this->generatePaginate ( $listaAll );
	}

	//ACTION PARA PESQUISA DE TRANSAÇÕES
	public function searchTransactionAction ()
	{
		$search = $this->getRequest()->getParam ("searchTra");

		$status = $this->getRequest()->getParam ("status");

		$date = $this->getRequest()->getParam ("initial");

		$date2 = $this->getRequest()->getParam ("final");
		
		$city = $this->getRequest()->getParam ("city");
		
		echo $city;

		$initial = null;
		$final = null;

		if($date != null){
			$pi = explode('/',$date);
			$initial = $pi[2] . '-' . $pi[1] . '-' . $pi[0];
		}

		if($date2 != null){
			$pf = explode('/',$date2);
			$final = $pf[2] . '-' . $pf[1] . '-' . $pf[0];
			$final = date("Y-m-d\TH:i", strtotime("+1 days", strtotime($final)));
		}


		$adminBusiness = new AdminBusiness();

		$listaAll = $adminBusiness->getTransactions($search, $status, $initial, $final, $city);

		$this->view->listTransactions = $this->generatePaginate ( $listaAll );
	}

	//MOSTRA OS DETALHES DA TRANSAÇÕES A PARTIR DO ID INFORMADO
	public function transactionDetailAction(){
		$user = Zend_Auth::getInstance()->getStorage()->read();

		$this->_helper->layout->disableLayout();

		$adminBusiness = new AdminBusiness();

		$transaction = $this->getRequest()->getParam("transaction_id");

		Zend_Registry::get('adminLog')->info($user['name'].' Visualizou transação: '.$transaction);

		$this->view->items = $adminBusiness->getProductsByTransaction($transaction);

	}
	
	//ALTERA A QUANTIDADE DE TENTATIVAS DE ENTREGA
	public function changeAttemptsAction(){
		
		$adminBusiness = new AdminBusiness();
		
		$data = array(
			'attempts'			=>	$this->getRequest()->getParam('attempt'),
			'id_transaction' 	=>	$this->getRequest()->getParam('id_transaction')
		);
		
		$adminBusiness->changeAttempt($data);
		
		if($data['attempts'] == 3){
			$messageBusiness = new MessageBusiness();
			$info = $adminBusiness->getProductsByTransaction($data['id_transaction']);
			
			$messageBusiness->sendAttemptsMail($info);
		}
		
	}

	//Atualiza as transações do sistema
	public function updateTransactionAction(){
		LogPagSeguro::info("Preparando para atualização transações");

		$clientBusiness = new ClientBusiness();

		$transactionBusiness = new TransactionBusiness();

		$config = new Zend_Config_Ini('../application/configs/application.ini', 'production');

		$credentials = new PagSeguroAccountCredentials($config->pagSeguro->email, $config->pagSeguro->token);


		$transactions = $transactionBusiness->getOpenTransaction();

		foreach ($transactions as $transaction) {
			try{
				LogPagSeguro::info("Iniciando update da transação ".$transaction['id_transaction']);

				$transact = PagSeguroTransactionSearchService::searchByCode(
				$credentials,
				$transaction['id_transaction']
				);

				if($transactionBusiness->getTransactionById($transaction['id_transaction']) != null){


					$data = array(
						'date_update' => $transact->getLastEventDate(),
						'status' => $transact->getStatus()->getValue(),
					);

					$transactionBusiness->updateTransaction($data, $transaction['id_transaction']);

				}
				LogPagSeguro::info("Finalizando update da transação ".$transaction['id_transaction']);
			}catch (Exception $e){
				LogPagSeguro::info("Erro ao fazer update da transação ".$transaction['id_transaction']);
				LogPagSeguro::error($e);
			}
		}
	}

	//ACTION PARA CADASTRO DE NOVO PRODUTO
	public function newProductAction ()
	{
		$config = new Zend_Config_Ini('../application/configs/application.ini', 'production');
		
		$user = Zend_Auth::getInstance()->getStorage()->read();
		
		$dir = $config->products->image_upload;
		$get = $config->products->get_image;

		Zend_Registry::get('adminLog')->info($user['name'].' Iniciou tela administrativa / cadastro de produtos : ');
		$adminBusiness = new AdminBusiness();

		if(!$_POST) {
			$this->view->findAllCategories = $adminBusiness->getAllCategories();
			$this->view->findAllEnterprises = $adminBusiness->getAllEnterprises();
		} else {

			$foto = $_FILES["image"];

			// Se a foto estiver sido selecionada
			if (!empty($foto["name"])) {

				// Largura mÃ¡xima em pixels
				$largura = 150;
				// Altura mÃ¡xima em pixels
				$altura = 180;
				// Tamanho mÃ¡ximo do arquivo em bytes
				$tamanho = 1000;

				$error = null;
				// Verifica se o arquivo Ã© uma imagem
				if(!preg_match("/^image\/(pjpeg|jpeg|png|gif|bmp)$/", $foto["type"])){
					$error[1] = "Isso nÃ£o Ã© uma imagem.";
				}

				$enterptise=  $adminBusiness->getEnterpriseById($_POST['title']);
				$enterpriseName = md5($enterptise[0]['enterprise_name']);
				$path = md5($enterpriseName);
				$path = str_replace(" ", "-", $enterpriseName);
				$path = strtolower($path);

				$path = $this->retira_acentos($path);

				if(!file_exists($dir.$path))
				{
					mkdir ($dir.$path, 0777 );   // aqui e o diretorio aonde serÃ¡ criado tipo home/public-html/
				}


				// Se nÃ£o houver nenhum erro
				if (count($error) == 0) {

					$fotoName = $this->retira_acentos($foto['name']) ;

					// Pega extensÃ£o da imagem
					preg_match("/\.(gif|bmp|png|jpg|jpeg){1}$/i", $fotoName, $ext);

					// Gera um nome Ãºnico para a imagem
					$nome_imagem = md5(uniqid(time())) . "." . $ext[1];

					// Caminho de onde ficarÃ¡ a imagem
					$caminho_imagem = $dir.$path."/".$nome_imagem;

					// Faz o upload da imagem para seu respectivo caminho
					move_uploaded_file($foto["tmp_name"], $caminho_imagem);

				}
			}
			

			$array = array(
							"id_category" => $_POST['id_category'],
						   	"name" => $_POST['name'],
						   	"title" => $enterptise[0]['enterprise_name'],
						   	"description" => $_POST['desc'],
						   	"nationality" => $_POST['nationality'],
						   	"year" => $_POST['year'],
						   	"price" => $_POST['price'],
						   	"image" => $get.$path."/".$nome_imagem,
						   	"quantity" => $_POST['quantity'],
						   	"date_insert" => date('Y-m-d H:i:s'),
							"weight"	=> $_POST['weight'],
							"status" => '1');

			$adminBusiness->insertProducts($array);
		//	echo "<script>if(confirm('Produto cadastrado com sucesso!\\nDeseja cadastrar outro?'))location.href='../admin/new-product';else location.href='../admin'</script>";
		}
	}

	//ACTION PARA VER DETALHES DE UM DETERMINADO CLIENTE
	public function viewClientAction(){
		$user = Zend_Auth::getInstance()->getStorage()->read();

		$adminBusiness = new AdminBusiness();
		$id = $this->getRequest()->getParam('client');

		Zend_Registry::get('adminLog')->info($user['name'].' Visualizou cliente: '.$id);

		if($id != null) {

			$this->view->info = $adminBusiness->findClientById($id);
			$this->view->userType = $adminBusiness->getUserTypes();

		}
	}

	//ACTION PARA ALTERAR O TIPO DE USUÁRIO
	public function userTypeAction(){
		$user = Zend_Auth::getInstance()->getStorage()->read();

		$adminBusiness = new AdminBusiness();

		$userId = $this->getRequest()->getParam ("user");
		$userType = $this->getRequest()->getParam ("type");

		$adminBusiness->changeUserType($userId, $userType);

		Zend_Registry::get('adminLog')->info($user['name'].' Alterou perfil de usuário: '.$userId.' para '.$userType);

	}
	
	//ACTION PARA EDITAR UM DETERMINADO PRODUTO
	public function editAction() {
		$config = new Zend_Config_Ini('../application/configs/application.ini', 'production');
		
		$adminBusiness = new AdminBusiness();

		$enterptise=  $adminBusiness->getEnterpriseById($_POST['title']);
		
		$dir = $config->products->image_upload;
		$get = $config->products->get_image;
		
		if($_POST) {
			$save_path = null;

			$foto = $_FILES["image"];

			$teste = $this->getRequest()->getParam ("title");

			// Se a foto estiver sido selecionada
			if (!empty($foto["name"])) {

				// Largura mÃ¡xima em pixels
				$largura = 150;
				// Altura mÃ¡xima em pixels
				$altura = 180;
				// Tamanho mÃ¡ximo do arquivo em bytes
				$tamanho = 1000;

				$error = null;
				// Verifica se o arquivo Ã© uma imagem
				if(!preg_match("/^image\/(pjpeg|jpeg|png|gif|bmp)$/", $foto["type"])){
					$error[1] = "Isso nÃ£o Ã© uma imagem.";
				}

				$enterpriseName = md5($enterptise[0]['enterprise_name']);
				$path = md5($enterpriseName);
				$path = str_replace(" ", "-", $enterpriseName);
				$path = strtolower($path);

				$path = $this->retira_acentos($path);

				if(!file_exists($dir.$path))
				{
					mkdir ($dir.$path, 0777 );   // aqui e o diretorio aonde serÃ¡ criado tipo home/public-html/
				}


				// Se nÃ£o houver nenhum erro
				if (count($error) == 0) {

					$fotoName = $this->retira_acentos($foto['name']) ;

					// Pega extensÃ£o da imagem
					preg_match("/\.(gif|bmp|png|jpg|jpeg){1}$/i", $fotoName, $ext);

					// Gera um nome Ãºnico para a imagem
					$nome_imagem = md5(uniqid(time())) . "." . $ext[1];

					// Caminho de onde ficarÃ¡ a imagem
					$caminho_imagem = $dir.$path."/".$nome_imagem;

					// Faz o upload da imagem para seu respectivo caminho
					move_uploaded_file($foto["tmp_name"], $caminho_imagem);

					$save_path = $dir.$path."/".$nome_imagem;

				}
			}

			$array = array(
				"id_product" => $_POST['id_product'],
				"id_category" => $_POST['id_category'],
			   "name" => $_POST['name'],
			   "title" => $enterptise[0]['enterprise_name'],
			   "description" => $_POST['desc'],
			   "nationality" => $_POST['nationality'],
			   "year" => $_POST['year'],
			   "price" => $_POST['price'],
			   "image" => $get.$path."/".$nome_imagem,
			   "quantity" => $_POST['quantity'],
			   "date_insert" => date('Y-m-d H:i:s'),
				"weight"	=> $_POST['weight'],
			   "status" => '1');
			$adminBusiness->editProducts($array);
			
			echo "<script>if(confirm('Produto Atualizado com sucesso!'))location.href='../admin';else location.href='../admin'</script>";
		}
	}

	//ACTION QUE MOSTRA OS DETALHES DE UM PRODUTO
	public function viewEditAction(){
		$adminBusiness = new AdminBusiness();
		$id = $this->getRequest()->getParam('product');

		if($id != null) {

			$this->view->findAllCategories = $adminBusiness->getAllCategories();
			$this->view->findAllEnterprises = $adminBusiness->getAllEnterprises();
			$this->view->info = $adminBusiness->findProductById($id);

		}
	}

	//ACTION PARA ALTERAR O STATUS DO PRODUTO(DISPONÍVEL, INDISPONÍVEL)
	public function changeAction() {
		$user = Zend_Auth::getInstance()->getStorage()->read();

		if($_GET['id'] && $_GET['status']) {
			$adminBusiness = new AdminBusiness();
			$adminBusiness->changeProductStatus($_GET['id'], $_GET['status']);

			Zend_Registry::get('adminLog')->info($user['name'].' Alterou status do produto : '.$_GET["id"].' para '.$_GET["status"]);
		}
	}

	//ACTION PARA CADASTRAR UMA NOVA EMPRESA NO SISTEMA
	public function newEnterpriseAction(){
		$user = Zend_Auth::getInstance()->getStorage()->read();

		Zend_Registry::get('adminLog')->info($user['name'].' Iniciou tela administrativa / nova empresa ');

		$adminBusiness = new AdminBusiness();

		if($_POST){
			$array = array("enterprise_name" => $_POST['enterprise']);

			$adminBusiness->insertEnterptise($array);

			Zend_Registry::get('adminLog')->info($user['name'].' Adicionou nova empresa: '.$_POST['enterprise']);
		}
	}

	//ACTION PARA DELETAR UMA EMPRESA DO SISTEMA
	public function deleteEnterpriseAction(){
		$this->_helper->layout->disableLayout();
		$user = Zend_Auth::getInstance()->getStorage()->read();

		$id = $this->getRequest()->getParam("enterprise_id");

		Zend_Registry::get('adminLog')->info($user['name'].' Preparou para deletar empresa ');

		$adminBusiness = new AdminBusiness();

		if($id != null){
			$adminBusiness->deleteEnterptise($id);

			Zend_Registry::get('adminLog')->info($user['name'].' Deletou uma empresa');

			$this->view->listEnterprises = $adminBusiness->getAllEnterprises();
		}

	}

	//ACTION PARA DELETAR UMA CATEGORIA DO SISTEMA
	public function deleteCategoryAction(){
		$this->_helper->layout->disableLayout();
		$user = Zend_Auth::getInstance()->getStorage()->read();

		$id = $this->getRequest()->getParam("id_category");

		Zend_Registry::get('adminLog')->info($user['name'].' Preparou para deletar empresa ');

		$adminBusiness = new AdminBusiness();

		if($id != null){
			$adminBusiness->deleteCategory($id);

			Zend_Registry::get('adminLog')->info($user['name'].' Deletou uma empresa');

			$this->view->listCategories = $adminBusiness->getAllCategories();
		}

	}

	//ACTION PARA CADASTRAR UMA CATEGORIA DO SISTEMA
	public function newCategoryAction(){
		$user = Zend_Auth::getInstance()->getStorage()->read();

		Zend_Registry::get('adminLog')->info($user['name'].' Iniciou tela administrativa / nova categoria ');

		$adminBusiness = new AdminBusiness();

		if($_POST){
			$array = array("desc" => $_POST['category']);

			$adminBusiness->insertCategory($array);

			Zend_Registry::get('adminLog')->info($user['name'].' Adicionou nova categoria: '.$_POST['category']);
		}
	}

	function retira_acentos( $texto )
	{
		$array1 = array(   "á", "à", "â", "ã", "ä", "é", "è", "ê", "ë", "í", "ì", "î", "ï", "ó", "ò", "ô", "õ", "ö", "ú", "ù", "û", "ü", "ç"
		, "Á", "À", "Â", "Ã", "Ä", "É", "È", "Ê", "Ë", "Í", "Ì", "Î", "Ï", "Ó", "Ò", "Ô", "Õ", "Ö", "Ú", "Ù", "Û", "Ü", "Ç", "_" );
		$array2 = array(   "a", "a", "a", "a", "a", "e", "e", "e", "e", "i", "i", "i", "i", "o", "o", "o", "o", "o", "u", "u", "u", "u", "c"
		, "A", "A", "A", "A", "A", "E", "E", "E", "E", "I", "I", "I", "I", "O", "O", "O", "O", "O", "U", "U", "U", "U", "C", "-" );
		return str_replace( $array1, $array2, $texto );
	}

	private function generatePaginate($list) {
		//Atributos financialPlan - Lista completa de Planos financeiros
		//Recupera o config
		$config = $this->getInvokeArg ( 'bootstrap' )->getOptions ();
		// PÃ¡gina que a paginaÃ§Ã£o irÃ¡ iniciar
		$pagina = intval ( $this->_getParam ( 'pagina', 1 ) );
		$paginator = Zend_Paginator::factory ( $list );
		//Seta a quantidade de registros por pÃ¡gina
		$paginator->setItemCountPerPage ( 10 );
		$paginator->setPageRange ( $config ['pagination'] ['page_range'] );
		// Seta a pÃ¡gina atual
		$paginator->setCurrentPageNumber ( $pagina );
		// Passa o paginator para a view
		return $paginator;
	}

}


